package cn.com.open.opensaas.scoreservice.service.impl;

import cn.com.open.opensaas.scoreservice.common.QuestionConstant;
import cn.com.open.opensaas.scoreservice.enums.MapGetType;
import cn.com.open.opensaas.scoreservice.mapper.QuestionContentMapper;
import cn.com.open.opensaas.scoreservice.logic.QuestionJudgeFactory;
import cn.com.open.opensaas.scoreservice.service.QuestionContentService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("questionContentService")
public class QuestionContentServiceImpl implements QuestionContentService {

    @Autowired
    private QuestionContentMapper questionContentMapper;

    /**
     * 根据Ids批量获取QuestionContent
     *
     * @param questionIds
     * @return
     */
    @Override
    public List<Map<String, Object>> findDBQuestionByIds(List questionIds) {
        return questionContentMapper.findDBQuestionByIds(questionIds);
    }

    /**
     * 判分逻辑
     *
     * @param questionList
     * @return
     */
    @Override
    public Map<String, Object> judge(List<Map<String, Object>> questionList) {
        //存储最终返回值
        Map<String, Object> resultMap = new LinkedHashMap<>();
        //存储库中不存在的试题Id
        StringBuilder noExistQuest = new StringBuilder();
        //存储所有试题总分
        Double totalScore = 0.0;

        //用来存储Data关键值中的数据
        Map<String, Object> dataMap = new HashMap<>();
        //用来存储Data中Items关键值中的数据
        List<Map<String, Object>> itemsList = new ArrayList<>();

        //批量获取数据库中对应学生答案试题数据
        List<Map<String, Object>> dbQuestionList = batchFindDbQuestion(questionList);

        //循环试题List
        for (Map<String, Object> question : questionList) {
            String contentJson = null;
            //循环DB试题List,向contentJson赋值
            for (Map<String, Object> dbQuestion : dbQuestionList) {
                if ((dbQuestion.get("questionId").toString().toLowerCase()).equals(question.get(QuestionConstant.ITEM_IDENTIFIER))) {
                    contentJson = (String) dbQuestion.get("contentJson");
                    break;
                }
            }
            //调用单个试题判分方法
            Map<String, Object> map = judgeQuestion(question, contentJson);
            //不存在试题Id
            String noExistQuestId = (String) map.get(MapGetType.NOEXISTQUESTID.getDisplay());
            if (!StringUtils.isBlank(noExistQuestId)) {
                noExistQuest.append(noExistQuestId+",");
            } else {
                //获取单题信息
                Map<String, Object> itemMap = (Map<String, Object>) map.get(MapGetType.ITEMMAP.getDisplay());
                double score = (Double) itemMap.get(QuestionConstant.STUDENT_ANSWER_SCORE);
                totalScore += score;//记入试题列表总分
                itemsList.add(itemMap);
            }
        }
        dataMap.put("TotalScore", totalScore);
        dataMap.put("Items", itemsList);

        resultMap.put("Data", dataMap);
        resultMap.put("Code", 0);
        if (StringUtils.isNotBlank(noExistQuest.toString())) {
            resultMap.put("Message", "没有找到的试题ID【" + noExistQuest.substring(0, noExistQuest.length() - 1) + "】");
        } else {
            resultMap.put("Message", noExistQuest);
        }

        return resultMap;
    }

    /**
     * 根据学生答案批量获取数据库中对应数据
     *
     * @param questionList
     * @return
     */
    @Override
    public List<Map<String, Object>> batchFindDbQuestion(List<Map<String, Object>> questionList) {
        //用来存储questionList中Id集合，用于批量获取数据库中对应数据
        List questionIds = new ArrayList();
        for (Map<String, Object> question : questionList) {
            questionIds.add(question.get(QuestionConstant.ITEM_IDENTIFIER));
        }
        if (questionIds.isEmpty()) {
            questionIds.add("");
        }
        //调用数据库查询(key-questionId value-contentJson)
        return findDBQuestionByIds(questionIds);
    }

    /**
     * 单题判分逻辑(新版)
     *
     * @param question
     * @param contentJson
     * @return
     */
    @Override
    public Map<String, Object> judgeQuestion(Map<String, Object> question, String contentJson) {
        //返回给调用的map(包含noExistQuest,itemMap)
        Map<String, Object> map = new HashMap<>();
        //创建判分工厂
        QuestionJudgeFactory questionJudgeFactory = new QuestionJudgeFactory();
        //存储库中不存在的试题Id
        String noExistQuestId = "";
        //用来存储Data中Items关键值中每个question的数据
        Map<String, Object> itemMap = new HashMap<>();
        //根据question.get("I1")在表QuestionContent中查询对应试题
        if (contentJson == null) {
            noExistQuestId = (String) question.get(QuestionConstant.ITEM_IDENTIFIER);
        } else {
            contentJson = contentJson.replace("\\\\\"", "'").replace("\\", "");
            //如果查询json失败
            if (contentJson == null || contentJson.isEmpty()) {
                map.put(MapGetType.NOEXISTQUESTID.getDisplay(), noExistQuestId);
                map.put(MapGetType.ITEMMAP.getDisplay(), itemMap);
                return map;
            }
            //反序列化成map
            Map<String, Object> dbQuestion = (Map<String, Object>) JSONObject.fromObject(contentJson);
            questionJudgeFactory.judge(question, dbQuestion, itemMap);
        }
        //将单题得分信息及不存在试题Id存入Map
        map.put(MapGetType.NOEXISTQUESTID.getDisplay(), noExistQuestId);
        map.put(MapGetType.ITEMMAP.getDisplay(), itemMap);
        return map;
    }
}